﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace DataFiller.DataStorage.Extension.ExcelOperator
{
    //config 1: sheet name
    //2. begin and end cell index for "row per instance",
    //or begin and end row number for "cell per instance"
    //3. header range
    //4. region begin row number or cell index
    //5. property path
    public class ExcelImporter
    {
        public virtual void DataImport<T>(IExcelbook workBook, string sheetName, int[] headerRowIndexs, Func<T> preFill, Action<T> postFill)
        {
            var sheet = workBook.GetSheet(sheetName);

            int minHeaderIndex = headerRowIndexs.Min();
            int maxHeaderIndex = headerRowIndexs.Max();
            foreach (IExcelRow row in sheet)
            {
                if (row.RowNum < minHeaderIndex)
                {
                    continue;
                }
                else if (row.RowNum <= maxHeaderIndex)
                {
                    mapperCollection.AddRange
                    (
                        GetMapperCollection(row).ToList()
                    );

                    continue;
                }

                T model = preFill();

                mapperCollection.ForEach
                    (
                        mapper => mapper.SetValue(row, model)
                    );

                postFill(model);
            }
        }

        //protected virtual IEnumerable<ExcelPropertyLocator> GetMapperCollection(IRow row)
        //{
        //    var headerCells = row.Cells.Where(cell => !string.IsNullOrEmpty(cell.StringCellValue));

        //    IEnumerable<Tuple<PropertyInfo, ColumnNameAttribute>> materials = typeof(FixedAssetInfo).GetProperties()
        //        .Where
        //        (
        //            p => p.GetCustomAttributes(typeof(ColumnNameAttribute), false).FirstOrDefault() != null
        //        )
        //        .Select
        //        (
        //            p => new Tuple<PropertyInfo, ColumnNameAttribute>(
        //            item1: p,
        //            item2: (ColumnNameAttribute)p.GetCustomAttributes(typeof(ColumnNameAttribute), false).First()
        //            )
        //        );

        //    IEnumerable<ICell> availableCells = headerCells.Where
        //        (
        //            cell => materials.FirstOrDefault(
        //                materia => materia.Item2.ColumnName == cell.StringCellValue) != null
        //        );

        //    return availableCells.Select(
        //        cell => new ExcelPropertyLocator
        //        {
        //            Key = cell.ColumnIndex,
        //            PropertyInfo = materials.First(p => p.Item2.ColumnName == cell.StringCellValue).Item1
        //        }
        //    );
        //}
    }
}
